<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="试卷的名称" prop="nama">
        <el-input
          v-model="queryParams.nama"
          placeholder="请输入试卷的名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['papers:papers:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['papers:papers:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="papersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名" align="center" prop="courseName" />
      <el-table-column label="试卷的名称" align="center" prop="nama" />
      <el-table-column label="试卷的总分值" align="center" prop="totalScored" />
      <el-table-column label="时间限制" align="center" prop="timeLimit" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="onclick(scope.row)">
            考试详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-flag"
            @click="Arrange(scope.row)"
          >
            考试安排
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="onachievement(scope.row)"
          >
            查看考试情况
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷作业对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="试卷的名称" prop="nama">
          <el-input v-model="form.nama" placeholder="请输入试卷的名称" />
        </el-form-item>
        <!-- <el-form-item label="试卷的总分值" prop="totalScored">
          <el-input
            v-model="form.totalScored"
            placeholder="请输入试卷的总分值"
          />
        </el-form-item>
        <el-form-item label="时间限制" prop="timeLimit">
          <el-input
            v-model="form.timeLimit"
            placeholder="请输入完成试卷的时间限制"
          />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 考试安排 -->
    <el-dialog
      title="考试安排"
      :visible.sync="ArrangeState"
      width="800px"
      append-to-body
    >
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="120px">
        <el-form-item label="试卷的名称" prop="name">
          <el-input
            v-model="form1.name"
            placeholder="请输入试卷的名称"
            disabled
          />
        </el-form-item>
        <el-form-item label="考生" prop="userIds">
          <el-select
            v-model="form1.userIds"
            filterable
            multiple
            placeholder="请选择考生"
          >
            <el-option
              v-for="item in options"
              :key="item.userId"
              :label="item.phonenumber"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ArrangeTrue"> 确 定 </el-button>
        <el-button @click="ArrangeState = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看考试成绩 -->
    <el-dialog
      title="考试成绩"
      :visible.sync="achievementState"
      width="800px"
      append-to-body
    >
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="考生姓名" align="center" prop="nickName" />
        <el-table-column label="试卷的名称" align="center" prop="paperNama" />
        <el-table-column
          label="试卷的总分值"
          align="center"
          prop="totalScored"
        />
        <el-table-column
          label="时间限制(分钟)"
          align="center"
          prop="timeLimit"
        />
        <el-table-column label="试卷得分值" align="center" prop="totalScore">
          <template slot-scope="scope">
            <span>{{
              scope.row.totalScore == 0 ? "-" : scope.row.totalScore
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所用时间(分钟)" align="center" prop="timeTaken">
          <template slot-scope="scope">
            <span>
              {{ scope.row.timeTaken == 0 ? "-" : scope.row.timeTaken }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.totalScore != 0"
              @click="onhandleUpdate(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 试卷详情 -->
    <el-dialog
      title="试卷详情"
      :visible.sync="testPaperState"
      width="800px"
      append-to-body
    >
      <p style="text-align: center">
        {{ testPaper.nama }} （总分：{{ testPaper.totalScored }}）（时间：{{
          testPaper.timeLimit
        }}分钟）
      </p>
      <!-- type 1 ‘主观题’ 2 '单选题' 3 '填空题' 4 '多选题'-->
      <div
        class="item"
        v-for="(item, index) in testPaper.questionList"
        :key="index"
      >
        <p>{{ index + 1 }} 、 {{ item.content }}? （{{ item.score }}分数）</p>
        <el-input
          v-if="item.type == '1'"
          type="textarea"
          resize="none"
          v-model="item.value"
          placeholder="请输入内容"
        ></el-input>
        <el-radio-group v-else-if="item.type == '2'" v-model="item.value">
          <el-radio
            v-for="(option, index) in item.optionsList"
            :key="option.isCorrect"
            :label="option.content"
          >
            {{ option.content }}
          </el-radio>
        </el-radio-group>
        <el-input
          v-else-if="item.type == '3'"
          v-model="item.value"
          placeholder="请输入"
        ></el-input>
        <el-checkbox-group v-else v-model="item.value">
          <el-checkbox
            :label="option.content"
            v-for="option in item.optionsList"
          ></el-checkbox>
        </el-checkbox-group>
      </div>
    </el-dialog>

    <!-- 试卷考试详情 -->
    <el-dialog
      title="考试"
      :visible.sync="testState"
      width="800px"
      append-to-body
    >
      <p style="text-align: center">
        {{ ywPapers.nama }} （总分：{{ ywPapers.totalScored }}）（时间：{{
          ywPapers.timeLimit
        }}分钟）
      </p>
      <!-- type 1 ‘主观题’ 2 '单选题' 3 '填空题' 4 '多选题'-->
      <div
        class="item"
        v-for="(item, index) in paperStudentAnswersList"
        :key="index"
      >
        <p>
          {{ index + 1 }} 、 {{ item.questionContent }}? （{{
            item.questionScore
          }}分数）{{
            (item.questionType == "1" || item.questionType == "3") &&
            !item.incomeScore
              ? "待定"
              : item.isCorrect == "1"
              ? "正确"
              : "错误"
          }}
          考生得分：{{ item.incomeScore }}
        </p>
        <el-input
          v-if="item.questionType == '1'"
          type="textarea"
          resize="none"
          v-model="item.value"
          placeholder="请输入内容"
          disabled
        ></el-input>
        <el-radio-group
          v-else-if="item.questionType == '2'"
          v-model="item.value"
          disabled
        >
          <el-radio
            v-for="(option, index) in item.optionsList"
            :key="option.optionId"
            :label="option.optionId"
          >
            {{ option.content }}
          </el-radio>
        </el-radio-group>
        <el-input
          v-else-if="item.questionType == '3'"
          v-model="item.value"
          placeholder="请输入"
          disabled
        ></el-input>
        <el-checkbox-group v-else v-model="item.value" disabled>
          <el-checkbox
            :label="option.optionId"
            v-for="option in item.optionsList"
            >{{ option.content }}</el-checkbox
          >
        </el-checkbox-group>

        <div
          v-if="
            (item.questionType == '1' || item.questionType == '3') &&
            !item.incomeScore
          "
          style="display: flex; margin-top: 10px"
        >
          <el-input-number
            v-model="item.input"
            :min="0"
            :max="item.questionScore"
            label="请输入分数"
          ></el-input-number>
          <el-button
            type="primary"
            @click="OnSure(item)"
            style="margin-left: 20px"
            >提交</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPapers,
  getPapers,
  delPapers,
  addPapers,
  updatePapers,
} from "@/api/papers/papers";

import {
  initiateTest,
  getPapersInfo,
  selectTeacher,
  paperResults,
  getInfoBack,
  awardingOfPoints,
} from "@/api/examination/examination";

export default {
  name: "Papers",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷作业表格数据
      papersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nama: null,
        courseId: null,
        courseName: null,
        active: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nama: [
          { required: true, message: "试卷的名称不能为空", trigger: "blur" },
        ],
      },

      // 考试安排
      form1: {
        name: "",
        userIds: [], // 选择向谁发起考试数组
        paperId: "", // 试卷表id
      },
      // 表单校验
      rules1: {
        userIds: [
          {
            type: "array",
            required: true,
            message: "请至少选择一名考生",
            trigger: "change",
          },
        ],
      },
      ArrangeState: false,
      options: [],

      // 查看考试成绩
      achievementState: false,
      achievementList: [],
      tableData: [],

      // 试卷详情
      testPaperState: false,
      testPaper: {},

      // 考试完成 (修改试卷)
      rowDate: {},
      testState: false,
      paperStudentAnswersList: [],
      ywPapers: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询试卷作业列表 */
    getList() {
      this.loading = true;
      listPapers(this.queryParams).then((response) => {
        this.papersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paperId: null,
        nama: null,
        totalScored: null,
        timeLimit: null,
        courseId: null,
        active: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.paperId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试卷作业";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const paperId = row.paperId || this.ids;
      getPapers(paperId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改试卷作业";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.paperId != null) {
            updatePapers(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPapers(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paperIds = row.paperId || this.ids;
      this.$modal
        .confirm('是否确认删除试卷作业编号为"' + paperIds + '"的数据项？')
        .then(function () {
          return delPapers(paperIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "papers/papers/export",
        {
          ...this.queryParams,
        },
        `papers_${new Date().getTime()}.xlsx`
      );
    },
    /** 安排考生考试 */
    Arrange(row) {
      selectTeacher(row.paperId).then((res) => {
        if (res.code == 200) {
          this.options = res.data;
          this.form1.name = row.nama;
          this.form1.paperId = row.paperId;
          this.ArrangeState = true;
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },
    ArrangeTrue() {
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          let obj = {
            paperId: this.form1.paperId,
            userIds: this.form1.userIds,
          };
          initiateTest(obj).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("提交成功");
              this.form1.name = "";
              this.form1.userIds = []; // 选择向谁发起考试数组
              this.form1.paperId = ""; // 试卷表id
              this.ArrangeState = false;
            } else {
              this.$modal.msgError(response.msg);
            }
          });
        }
      });
    },
    /** 查看考试成绩 */
    onachievement(row) {
      paperResults({
        paperId: row.paperId,
      }).then((res) => {
        // console.log(res.rows, "shujushuju");
        this.tableData = res.rows;
        this.achievementState = true;
      });
    },

    /** 试卷详情 */
    onclick(row) {
      getPapersInfo(row.paperId).then((res) => {
        if (res.code == 200) {
          this.testPaper = res.data;
          this.testPaperState = true;
          this.testPaper.questionList = res.data.questionList.map((element) => {
            return {
              ...element,
              value: element.type === "4" ? [] : "",
            };
          });

          console.log(this.testPaper, "shuju");
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },

    /** */
    onhandleUpdate(row) {
      this.rowDate = row;
      getInfoBack({ paperId: row.paperId, userId: row.studentId }).then(
        (res) => {
          this.testState = true;
          this.ywPapers = res.data.ywPapers;

          // 线根据 questionId 问题ID对返回数组进行去重
          const uniqueArray = res.data.paperStudentAnswersList.reduce(
            (acc, current) => {
              const x = acc.find(
                (item) => item.questionId === current.questionId
              );
              if (!x) {
                return acc.concat([current]);
              } else {
                return acc;
              }
            },
            []
          );

          let arr = [];
          for (let i = 0; i < uniqueArray.length; i++) {
            let element = uniqueArray[i];
            if (element.questionType === "4") {
              let xuan = [];
              for (
                let j = 0;
                j < res.data.paperStudentAnswersList.length;
                j++
              ) {
                let nav = res.data.paperStudentAnswersList[j];
                if (nav.questionId === element.questionId) {
                  xuan.push(nav.optionId);
                }
              }
              arr.push({
                ...element,
                value: xuan,
                input: "",
              });
            } else if (element.questionType === "2") {
              arr.push({ ...element, value: element.optionId, input: "" });
            } else {
              arr.push({ ...element, value: element.answerText, input: "" });
            }
          }
          // 判断多选题，是否正确
          for (let n = 0; n < arr.length; n++) {
            let content = arr[n];
            if (content.questionType == "4") {
              for (let index = 0; index < content.value.length; index++) {
                let kroi = content.value[index];
                for (let k = 0; k < content.optionsList.length; k++) {
                  if (
                    kroi == content.optionsList[k].optionId &&
                    content.optionsList[k].isCorrect == "2"
                  ) {
                    content.isCorrect = "2";
                    return false;
                  }
                }
              }
            }
          }
          this.paperStudentAnswersList = arr;
        }
      );
    },
    OnSure(item) {
      console.log(item);
      // 分数限制

      // if (item.score > item.maxScore) {
      //   this.$message({
      //     message: "分数不能大于最大分数",
      //     type: "warning",
      //   });
      //   return false;
      // }

      let obj = {
        answerId: item.answerId,
        isCorrect: Number(item.input) > 0 ? "1" : "2", // 答案是否正确,
        score: Number(item.input), // 所得分数
      };
      awardingOfPoints(obj).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.onhandleUpdate(this.rowDate);
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
  },
};
</script>
